﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ShopBLL;
using ShopModel;

public partial class OrderConfirmation : BasePage
{
    #region METHODS

    private void ShowCompanySection()
    {
        rowInvoiceData.Visible = true;
        rowCompanyAddress.Visible = true;
        rowCompanyName.Visible = true;
        rowNIP.Visible = true;
    }

    private void ShowError(string errorMessage)
    {
        lblInfo.Text = errorMessage + "<BR />" + string.Format(Resources.Language.OrderConfirmation_FaultPleaseCorrect, Resources.Language.Back);
        lblInfo.Visible = true;
    }

    private bool ValidateVoucher(Realization order)
    {
        string code;
        Voucher voucher;
        if (order.Voucher != null)
        {
            code = order.Voucher.Code.Replace("-", "").Substring(0, 8);
            voucher = OrderManager.Instance.GetVoucherByGuid(code, false);
            if (voucher != null)
                return true;
            else
                return false;
        }
        else return true;
    }

    #endregion METHODS

    #region EVENTS

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(Resources.Language.UrlOrderDetail.ToLower() + ".aspx");
    }

    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        Dictionary<int, BasketItem> basket = (Dictionary<int, BasketItem>)Session["BasketItems"];

        if (basket == null || basket.Count == 0)
        {
            ShowError(Resources.Language.CartIsEmpty);
            return;
        }

        if (Session["OrderData"] != null)
        {
            bool createNewAccount = false;
            object userId = null;
            Realization order = (Realization)Session["OrderData"];

            if (!ValidateVoucher(order))
            {
                ShowError(Resources.Language.VoucherErrorOccured);
                return;
            }

            if (User.Identity.IsAuthenticated)
            {
                userId = Membership.GetUser(true).ProviderUserKey;
                createNewAccount = false;
            }
            else
            {
                MembershipCreateStatus status;
                MembershipUser user = Membership.CreateUser(order.iCustomer.Email, order.iCustomer.Password, order.iCustomer.Email, order.iCustomer.Question, order.iCustomer.Answer, true, out status);
                if (status == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(user.UserName, "customer");
                    userId = (Guid)user.ProviderUserKey;
                    createNewAccount = true;
                }
                else
                {
                    switch (status)
                    {
                        case MembershipCreateStatus.DuplicateEmail:
                        case MembershipCreateStatus.DuplicateUserName:
                            ShowError(Resources.Language.NewClient_EmailDuplicate);
                            break;
                        case MembershipCreateStatus.InvalidUserName:
                        case MembershipCreateStatus.InvalidEmail:
                            ShowError(Resources.Language.NewClient_EmailInvalid);
                            break;
                        case MembershipCreateStatus.InvalidPassword:
                            ShowError(string.Format(Resources.Language.NewClient_PasswordInvalid, Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters));
                            break;
                        case MembershipCreateStatus.InvalidQuestion:
                            ShowError(Resources.Language.NewClient_QuestionInvalid);
                            break;
                        case MembershipCreateStatus.InvalidAnswer:
                            ShowError(Resources.Language.NewClient_AnswerInvalid);
                            break;
                        default:
                            ShowError(Resources.Language.Error_PleaseTryLater);
                            break;
                    }
                    return;
                }
            }

            order.UrlReferer = Session["URLRefferer"] != null ? (string)Session["URLRefferer"] : string.Empty;
            order.IDRealization = OrderManager.Instance.NewOrder(ref order, userId, createNewAccount);
            Session["OrderData"] = order;

            if (order.IDRealization > 0)
            {
                switch (order.Payment.PaymentGroup)
                {
                    case PaymentGroups.Online:
                        Response.Redirect(Resources.Language.UrlPayment.ToLower() + ".aspx");
                        break;
                    default:
                        Response.Redirect(Resources.Language.UrlOrderResult.ToLower() + ".aspx");
                        break;
                }
            }
        }
    }

    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Load(object sender, EventArgs e)
    {
        Realization order = (Realization)Session["OrderData"];

        if (order != null)
        {
            lblNameContent.Text = order.iCustomer.FirstName;
            lblSurnameContent.Text = order.iCustomer.Surname;
            lblStreetContent.Text = order.iCustomer.Street;
            lblCityContent.Text = order.iCustomer.ZipCode + " " + order.iCustomer.City;
            lblEmailContent.Text = order.iCustomer.Email;
            lblPhoneNumberContent.Text = order.iCustomer.Phone;
            lblCountryContent.Text = order.iCustomer.Country;
            lblCostContent.Text = String.Format("{0:F02} " + Resources.Language.Currency, order.TotalAmountBrutto);
            lblCountry.Visible = order.SendAbroad;
            lblCountryContent.Visible = order.SendAbroad;
            lblShipmentCostContent.Text = string.Format("{0:F02} " + Resources.Language.Currency, order.ShipmentCost);
            lblAllCostContent.Text = string.Format("{0:F02} " + Resources.Language.Currency, order.TotalAmountBrutto + order.ShipmentCost);


            lblPaymentContent.Text = order.Payment.PaymentName;

            if (order.Payment.PaymentGroup == PaymentGroups.Online)
            {
                lblPaymentContent.Text = Resources.Language.OnlinePayment;
                lblOnlinePayment.Visible = true;
                lblOnlinePaymentContent.Visible = true;
                lblOnlinePaymentContent.Text = order.Payment.PaymentName;
            }

            if (order.iCustomer.IsCompany)
            {
                ShowCompanySection();
                if (order.iCustomer.SameAddress)
                {
                    lblCompanyCityContent.Text = lblCityContent.Text;
                    lblCompanyStreetContent.Text = lblStreetContent.Text;
                }
                else
                {
                    lblCompanyCityContent.Text = order.iCustomer.CompanyZipCode + " " + order.iCustomer.CompanyCity;
                    lblCompanyStreetContent.Text = order.iCustomer.CompanyStreet;
                }
                lblCompanyNameContent.Text = order.iCustomer.CompanyName;
                lblNipContent.Text = order.iCustomer.CompanyNIP;
            }
        }
        else
            tblConfirmData.Visible = false;
    }

    #endregion PAGE EVENTS
}
